package jdbcForMe;

import jdbcForMe.setting.DBSetting;
import jdbcForMe.setting.ItemSetting;
import jdk.internal.org.objectweb.asm.Type;

import java.lang.reflect.Field;
import java.sql.*;

public class MyDB {
    //public
    public MyDB() {
        formString = new FormattedForm();
    }

    /**
     * @param url    a database url of the form
     * @param user   the database user on whose behalf the connection is being made
     * @param passwd the user's password
     */
    public MyDB(String url, String user, String passwd) throws SQLException {
        this.url = url;
        this.user = user;
        this.passwd = passwd;
        formString = new FormattedForm();
        conn = DriverManager.getConnection(url, user, passwd);
    }

    public MyDB(DBSetting dbs) throws SQLException {
        this.url = dbs.getUrl();
        this.user = dbs.getUser();
        this.passwd = dbs.getPasswd();
        formString = new FormattedForm();
        conn = DriverManager.getConnection(url, user, passwd);
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public void setUser(String user) {
        this.user = user;
    }

    public void setPasswd(String passwd) {
        this.passwd = passwd;
    }

    public void setConn(Connection conn) {
        this.conn = conn;
    }

    /**
     * @throws SQLException if a database access error occurs or the url is
     */
    public void createConnection() {
        try {
            DriverManager.getConnection(url, user, passwd);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

    /**
     * 增加
     * 删除
     * 修改
     * 查询
     */

    //item的属性必须跟建表时的顺序一样
    public void addValues(ItemSetting itemSetting) throws SQLException {
        //属性必须为public
        Field[] fields = itemSetting.getClass().getFields();
        StringBuilder initSql = new StringBuilder("insert into hotelData values(");
        for (int i = 0; i < fields.length; i++) {
            Type.getType(fields[i].getClass());
        }
        initSql.append(")");
        String preparedSql = initSql.toString();
        Statement st = conn.createStatement();
        st.execute(preparedSql);
    }



    //private
    private String url;
    private String user;
    private String passwd;
    private Connection conn;
    private FormattedForm formString;

    //测试类
    static class Test{
        public static void main(String[] args) {
            try {
                new MyDB("jdbc:mysql://localhost/crawl", "root", "12345678");
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }
}
